<%@ page import="com.mashape.unirest.http.JsonNode" %>
<%@ page import="com.mashape.unirest.http.Unirest" %>
<%@ page import="com.mashape.unirest.http.exceptions.UnirestException" %>
<%@ page import="com.tencent.albert.weixin.driver.Constants" %>
<%@ page import="com.tencent.albert.weixin.driver.MsgManager" %>
<%@ page import="com.tencent.albert.weixin.driver.bean.ReceivedMsgInfo" %>
<%@ page import="com.tencent.albert.weixin.driver.msg.resp.TransferServiceRespMessage" %>
<%@ page import="org.apache.commons.lang3.StringUtils" %>
<%@ page import="java.io.ByteArrayOutputStream" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="com.mashape.unirest.http.HttpResponse" %>
<%@ page import="com.tencent.albert.weixin.driver.utils.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%
    if (request.getMethod().equals("GET")) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        if (null != signature && signature.length() > 0) {
            if (WeixinUtil.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
            }
        }
    } else if (request.getMethod().equals("POST")) {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            // 将解析结果存储在HashMap中
            Map<String, String> requestMap = new HashMap<String, String>();
            // 从request中取得输入流
            InputStream inputStream = request.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i = -1;
            while ((i = inputStream.read()) != -1) {
                baos.write(i);
            }
            String temp = baos.toString();
            System.out.println("read post:" + temp);

            ReceivedMsgInfo msg = new ReceivedMsgInfo();
            msg.setReceivedContent(temp);
//            <xml><ToUserName><![CDATA[gh_78d3572c4f80]]></ToUserName>
//            <FromUserName><![CDATA[oKsEQuEerHMdwU3VvKyK7bgxe6pU]]></FromUserName>
//            <CreateTime>1423978567</CreateTime>
//            <MsgType><![CDATA[text]]></MsgType>
//            <Content><![CDATA[地方]]></Content>
//            <MsgId>6115941375738357275</MsgId>
//            </xml>

            String head = "<ToUserName><![CDATA[";
            int msgTypeStatPoint = temp.indexOf(head)+head.length();
            int msgTypeEndPoint = temp.indexOf("]]></ToUserName>",msgTypeStatPoint);
            String toUserName = temp.substring(msgTypeStatPoint,msgTypeEndPoint);

            head = "<FromUserName><![CDATA[";
            msgTypeStatPoint = temp.indexOf(head)+head.length();
            msgTypeEndPoint = temp.indexOf("]]></FromUserName>",msgTypeStatPoint);
            String fromUserName = temp.substring(msgTypeStatPoint,msgTypeEndPoint);

            head = "<MsgType><![CDATA[";
            msgTypeStatPoint = temp.indexOf(head)+head.length();
            msgTypeEndPoint = temp.indexOf("]]></MsgType>",msgTypeStatPoint);
            String msgType = temp.substring(msgTypeStatPoint,msgTypeEndPoint);

            head = "<Event><![CDATA[";
            msgTypeStatPoint = temp.indexOf(head)+head.length();
            msgTypeEndPoint = temp.indexOf("]]></Event>",msgTypeStatPoint);
            String event = "";
            if (msgTypeEndPoint >= msgTypeStatPoint) {
                event = temp.substring(msgTypeStatPoint,msgTypeEndPoint);
            } else {
            }


            head = "<EventKey><![CDATA[";
            msgTypeStatPoint = temp.indexOf(head)+head.length();
            msgTypeEndPoint = temp.indexOf("]]></EventKey>",msgTypeStatPoint);
            String eventKey = "";

            if (msgTypeEndPoint >= msgTypeStatPoint) {
                eventKey = temp.substring(msgTypeStatPoint,msgTypeEndPoint);
            } else {
            }

            if(!StringUtils.isEmpty(eventKey)){
                Report.send("运营部","lynn","数据统计","二维码关注",eventKey, fromUserName,"null","null","null","null");
                if (eventKey.contains("qrscene_")) {
                    String channel = eventKey.replace("qrscene_", "");
                    String url = "http://www.xiaoluo.com/pmsstat/public/dataReport";
                    try {
                        Unirest.get(url).queryString("event_type", "wechat")
                                .queryString("event_name", "scanqrcode")
                                .queryString("channel", channel).asBinary();
                    } catch (Exception e) {

                    }
                }
            }

//            // 读取输入流
//            SAXReader reader = new SAXReader();
//            Document document = reader.read(new ByteArrayInputStream(temp.getBytes("UTF-8")));
//            // 得到xml根元素
//            Element root = document.getRootElement();
//            // 得到根元素的所有子节点
//            List<Element> elementList = root.elements();
//            // 遍历所有子节点
//            for (Element e : elementList) {
//                requestMap.put(e.getName(), e.getText());
//            }
//            // 释放资源
//            inputStream.close();
//            inputStream = null;
//
//            String fromUserName = requestMap.get("FromUserName");
//            String toUserName = requestMap.get("ToUserName");
//            String msgType = requestMap.get("MsgType");
//
//            for (Map.Entry<String, String> entry : requestMap.entrySet()) {
//                System.out.println("......." + entry.getKey() + ":" + entry.getValue());
//            }
//            System.out.println("recv msg from " + fromUserName + " to " + toUserName + " msgType:" + msgType);

            if (msgType.equals(Constants.REQ_MESSAGE_TYPE_EVENT)) {
//                if (requestMap.get("Event").equals(Constants.EVENT_TYPE_JOBFINISH)) {
//                } else if (requestMap.get("Event").equals(Constants.EVENT_TYPE_UNSUBSCRIBE)) {
//                } else if (requestMap.get("Event").equals(Constants.EVENT_TYPE_SUBSCRIBE)) {
//                } else {
//                }
                if ( event.equals(Constants.EVENT_TYPE_CLICK)){

                    if(eventKey.equals("BTN_CLICK_FOR_0")){
                        String url = "请联系客服直接申请，客服热线：18312532077";
                        out.println("<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                                "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                                "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                                "</MsgType><Content><![CDATA["+url+"]]></Content></xml>");
                        msg.setResponseContent("");
                    } else if (eventKey.equals("BTN_CLICK_FOR_COOPERATE")) {
                        String url = "商务合作请联系杨小姐 电话/微信：18588207420，邮箱：bd@52xiaoluo.com";
                        out.println("<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                                "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                                "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                                "</MsgType><Content><![CDATA["+url+"]]></Content></xml>");
                        msg.setResponseContent("");
                    } else if (eventKey.equals("BTN_CLICK_FOR_2")) {
                        String url = "请添加“深圳租房小助手”个人号：18312532077，小编亲自上阵，帮你发布“找房”信息，覆盖万余深圳白领，快速匹配，省钱省时间。中介勿扰。";
                        out.println("<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                                "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                                "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                                "</MsgType><Content><![CDATA["+url+"]]></Content></xml>");
                        msg.setResponseContent("");
                    } else if (eventKey.equals("BTN_CLICK_FOR_3")) {
                        String url = "请添加“深圳租房小助手”个人号：18312532077，小编亲自上阵，帮你发布“转租”信息，覆盖万余深圳白领，快速匹配，省钱省时间。中介勿扰。";
                        out.println("<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                                "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                                "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                                "</MsgType><Content><![CDATA["+url+"]]></Content></xml>");
                        msg.setResponseContent("");
                    } else if (eventKey.equals("BTN_CLICK_FOR_4")) {
                        String url = "请添加“深圳租房小助手”个人号：18312532077，小编亲自上阵，帮你在朋友圈发布“招室友”信息，覆盖万余深圳白领，快速匹配，省钱省时间。中介勿扰。";
                        out.println("<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                                "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                                "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                                "</MsgType><Content><![CDATA["+url+"]]></Content></xml>");
                        msg.setResponseContent("");
                    } else if (eventKey.equals("BTN_CLICK_FOR_mishu")) {
                        String url = "上网找房看花眼？\n中介找房要收钱？\n免佣小秘书来帮你找！\n\n请微信回复【联系方式，想租哪里、预算多少】\n" +
                                "秘书MM会在15分钟内给你推荐合适房源，请到菜单栏“我的小螺-推荐房源”查看！\n\n我们的服务时间为 9:00–21:00。请叫我雷轰/大兵\n";

                        out.println("<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                                "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                                "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                                "</MsgType><Content><![CDATA["+url+"]]></Content></xml>");
                        msg.setResponseContent("");
                    }
                } else if ( event.equals(Constants.EVENT_TYPE_SUBSCRIBE) ) {
                    //String url = "你来啦~！\n\n找房找得崩溃了？[委屈]\n被中介骗了？[惊恐]\n室友不靠谱？[疯了]\n\n点下方【租房】，一切都会好起来的 [拥抱]\n\nhttp://url.cn/THhF5v\n";
                    //
                    //520元住好房，马上脱单↓↓
                    //String url = "单身狗福利[微笑]\n深圳爱情公寓等你来↓↓\n\nhttp://url.cn/WtfMQs\n";
                    //String url = "小螺带你玩：\n\n「首届职场吐槽大赛」\n 不看后悔哟↓↓↓\n\nhttp://url.cn/YE8Zzm";
                    //String url = "单身汪福利\n深圳爱情公寓限时招租↓\n\nhttp://www.52xiaoluo.com/home/rentalService/index";
                    //String url = "「跑男」空降深圳啦！\n小螺带你跑动全城+撕名牌\n\n报名链接↓↓\n\nhttp://dwz.cn/11Oz71";
                    //String url = "「跑男」空降深圳啦！\n小螺带你跑动全城+撕名牌\n\n活动详情↓↓\n\nhttp://www.dwz.cn/12UvxF";
                    //String url = "租房0押金？！\n入住小螺即可预约↓↓ \n\nhttp://dwz.cn/1eGGli";
                    //String start = "【双12年度盛典】\n\n刷颜值，赢豪宅↓↓↓ \n\n";
                    //String double12Url =  URLUtil.getShortUrl("http://m.xiaoluo.com/m/activity1212/faceScore?channel=wxhyy1209");
                    // String nanshan = "【南山】科技园、海岸城\n";
                    // String nanshanUrl = URLUtil.getShortUrl("http://m.xiaoluo.com/m/list?regionName=%E5%8D%97%E5%B1%B1%E5%8C%BA&src=wxhyy1116");
                    // String baoan = "【宝安】宝安中心、西乡\n";
                    // String baoanUrl =  URLUtil.getShortUrl("http://m.xiaoluo.com/m/list?regionName=%E5%AE%9D%E5%AE%89%E5%8C%BA&src=wxhyy1116");
                    // String futian = "【福田】市中心精品公寓\n";
                    // String futianUrl =  URLUtil.getShortUrl("http://m.xiaoluo.com/m/list?regionName=%E7%A6%8F%E7%94%B0%E5%8C%BA&src=wxhyy1116");
                    // String longhua = "【龙华】福田上班首选\n";
                    // String longhuaUrl =  URLUtil.getShortUrl("http://m.xiaoluo.com/m/list?regionName=%E9%BE%99%E5%8D%8E%E6%96%B0%E5%8C%BA&src=wxhyy1116");

                    //String url = start + double12Url;

                    //out.println("<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                    //"<FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                    //"<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                    //"</MsgType><Content><![CDATA["+url+"]]></Content></xml>");
                    //msg.setResponseContent("");

                    String start = "上网找房看花眼？\n中介找房要收钱？\n免佣小秘书来帮你找！\n\n请微信回复【联系方式，想租哪里、预算多少】\n" +
                            "秘书MM会在15分钟内给你推荐合适房源，请到菜单栏“我的小螺-推荐房源”查看！\n\n我们的服务时间为 9:00–21:00。请叫我雷轰/大兵";
                    String double12Url =  "";
                    //String double12Url =  URLUtil.getShortUrl("http://m.xiaoluo.com/m/activity1212/faceScore?channel=wxhyy1209");
                    String url = start + double12Url;

                    out.println("<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                            "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                            "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                            "</MsgType><Content><![CDATA["+url+"]]></Content></xml>");
                    msg.setResponseContent("");
                } else if ( event.equals("SCAN") ) {
                    // String nanshan = "【南山】科技园、海岸城\n";
                    // String nanshanUrl = URLUtil.getShortUrl("http://m.xiaoluo.com/m/list?regionName=%E5%8D%97%E5%B1%B1%E5%8C%BA&src=wxhyy1116");
                    // String baoan = "【宝安】宝安中心、西乡\n";
                    // String baoanUrl =  URLUtil.getShortUrl("http://m.xiaoluo.com/m/list?regionName=%E5%AE%9D%E5%AE%89%E5%8C%BA&src=wxhyy1116");
                    // String futian = "【福田】市中心精品公寓\n";
                    // String futianUrl =  URLUtil.getShortUrl("http://m.xiaoluo.com/m/list?regionName=%E7%A6%8F%E7%94%B0%E5%8C%BA&src=wxhyy1116");
                    // String longhua = "【龙华】福田上班首选\n";
                    // String longhuaUrl =  URLUtil.getShortUrl("http://m.xiaoluo.com/m/list?regionName=%E9%BE%99%E5%8D%8E%E6%96%B0%E5%8C%BA&src=wxhyy1116");
                    String start = "上网找房看花眼？\n中介找房要收钱？\n免佣小秘书来帮你找！\n\n请微信回复【联系方式，想租哪里、预算多少】\n" +
                            "秘书MM会在15分钟内给你推荐合适房源，请到菜单栏“我的小螺-推荐房源”查看！\n\n我们的服务时间为 9:00–21:00。请叫我雷轰/大兵";
                    String double12Url =  "";//URLUtil.getShortUrl("http://m.xiaoluo.com/m/activity1212/faceScore?channel=wxhyy1209");
                    String url = start + double12Url;

                    out.println("<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                            "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                            "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                            "</MsgType><Content><![CDATA["+url+"]]></Content></xml>");
                    msg.setResponseContent("");

                }

                else {
                    out.print("");
                    msg.setResponseContent("");
                }
            } else if (temp.indexOf("测试链接") > 0) {
                String title ="『免费领房租』趁年轻，住好点！！";
                String description ="这是一次免费领房租的“撕X”大战\r\n可以帮你减少每月薪资当中很大的一笔开支\r\n这笔钱会变成男朋友请你吃的一顿自助餐\r\n京基大厦100层一览深圳夜景\r\n或是一辆可以陪伴骑行时光的硬尾山地车\r\n也或者是一次浪漫的出国旅行";
                String picurl ="https://mmbiz.qlogo.cn/mmbiz/jW2u9NDw4KxnATodZ5sKL5sZugM8Mb83jSibe7dTsw81rD9AlByP3AmazFpjrOoWS0mzgKxBUyEvkkdV8NyRTww/0";
                String url ="http://www.52xiaoluo.com/user/collect/home";
                out.println("<xml>"+
                        "<ToUserName><![CDATA["+fromUserName+"]]></ToUserName>"+
                        "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>"+
                        "<CreateTime>1423984341</CreateTime>"+
                        "<MsgType><![CDATA[news]]></MsgType>"+
                        "<ArticleCount>1</ArticleCount>"+
                        "<Articles>"+
                        "<item>"+
                        "<Title><![CDATA["+title+"]]></Title>"+
                        "<Description><![CDATA["+description+"]]></Description>"+
                        "<PicUrl><![CDATA["+picurl+"]]></PicUrl>"+
                        "<Url><![CDATA["+url+"]]></Url>"+
                        "</item>"+
                        "</Articles>"+
                        "</xml>");
                msg.setResponseContent("");
            } else if (temp.indexOf("羽毛球") > 0) {
                String title ="小螺趣租 | 一起打羽毛球吧，周日约起来！";
                String description ="每周日晚7:30-9:30\r\n报名成功后请勿放鸽子，欢迎空降；\r\n七月活动免费，请自带球拍和水；\r\n仅限小螺班会员参加，限5个名额。";
                String picurl ="https://mmbiz.qlogo.cn/mmbiz/jW2u9NDw4KzBLXXYdJmmDdUbPl1ZLhQ8gUSaMrBS1qyKPOPvtQvWiaiaibE3TfAiclMFl7ofeLmGLSCeyC7uZjialVw/0";
                String url ="http://url.cn/dJdSMq";
                out.println("<xml>"+
                        "<ToUserName><![CDATA["+fromUserName+"]]></ToUserName>"+
                        "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>"+
                        "<CreateTime>1423984341</CreateTime>"+
                        "<MsgType><![CDATA[news]]></MsgType>"+
                        "<ArticleCount>1</ArticleCount>"+
                        "<Articles>"+
                        "<item>"+
                        "<Title><![CDATA["+title+"]]></Title>"+
                        "<Description><![CDATA["+description+"]]></Description>"+
                        "<PicUrl><![CDATA["+picurl+"]]></PicUrl>"+
                        "<Url><![CDATA["+url+"]]></Url>"+
                        "</item>"+
                        "</Articles>"+
                        "</xml>");
                msg.setResponseContent("");
            } else if (temp.indexOf("testtest") > 0) {
                String url = "你来啦~！\n\n参加中影送礼活动请点↓\nhttp://url.cn/VQUfTp\n\n找房小分队看这里↓↓↓\n\n点下方【我要】-【租房】，趁年轻，住好点。[得意]\n";
                out.println("<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                        "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                        "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                        "</MsgType><Content><![CDATA["+url+"]]></Content></xml>");
                msg.setResponseContent("");
            } else if (temp.indexOf("跑男") > 0) {
                String url = "【跑男】活动已结束，谢谢您的关注 :-)";
                out.println("<xml><ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>" +
                        "<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>" +
                        "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                        "</MsgType><Content><![CDATA[" + url + "]]></Content></xml>");
                msg.setResponseContent("");
            } else if (temp.indexOf("门票") > 0) {
                String url = "活动已结束，谢谢您的关注~";
                out.println("<xml><ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>" +
                        "<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>" +
                        "<CreateTime>1423984341</CreateTime><MsgType><![CDATA[text]]>" +
                        "</MsgType><Content><![CDATA[" + url + "]]></Content></xml>");
                msg.setResponseContent("");

                Report.send("运营部","kitty","数据统计","门票", null, fromUserName,"null","null","null","null");
            }

            //else if (temp.indexOf("正式") > 0) {
            //String title1 = "【12.12元起租】小螺趣租年度盛典，演唱会门票周周送";
            //String desc1 = "【12.12元起租】小螺趣租年度盛典，演唱会门票周周送";
            //String picUrl1 = "http://img.52xiaoluo.com/1212wxhyy04.jpg";
            //String url1 = "http://mp.weixin.qq.com/s?__biz=MzA4ODEwNTc3MA==&mid=439811770&idx=2&sn=a4d21c1c534ea53b27c6034d431688bc&scene=1&srcid=12095LM6qZD2VT3kGXIr0R49#wechat_redirect";
            //String title2 = "颜值高的都刷脸换豪宅了，你却还在刷气质";
            //String desc2 = "颜值高的都刷脸换豪宅了，你却还在刷气质";
            //String picUrl2 = "http://img.52xiaoluo.com/1212wxhyy02.jpg";
            //String url2 = "http://mp.weixin.qq.com/s?__biz=MzA4ODEwNTc3MA==&mid=439811770&idx=1&sn=3f2c4a28464cf8538ae59dece96b841c&scene=1&srcid=1209QfeMI79UKdClM3k7dfL5#wechat_redirect";
            //String push = "<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName><FromUserName><![CDATA["+toUserName+"]]></FromUserName><CreateTime>1423984341</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>2</ArticleCount><Articles><item><Title><![CDATA["+title1+"]]></Title><Description><![CDATA["+desc1+"]]></Description><PicUrl><![CDATA["+picUrl1+"]]></PicUrl><Url><![CDATA["+url1+"]]></Url></item><item><Title><![CDATA["+title2+"]]></Title><Description><![CDATA["+desc2+"]]></Description><PicUrl><![CDATA["+picUrl2+"]]></PicUrl><Url><![CDATA["+url2+"]]></Url></item></Articles></xml>";
            //out.println(push);
            //msg.setResponseContent("");
            //}
            else {
                TransferServiceRespMessage respMessage = new TransferServiceRespMessage();
                respMessage.setToUserName(fromUserName);
                respMessage.setFromUserName(toUserName);
                respMessage.setCreateTime(new Date().getTime());
                String respContent = respMessage.toXmlString();
                out.print(respContent);
                msg.setResponseContent(respContent);
            }
            MsgManager.addReceivedMsg(msg);
        } catch (Exception e) {
            e.printStackTrace();
            JspLogger.info("oauth","receive msg error "+e,e);
        }
    }

%>
